layui.use(['form','tree','element','table','laytpl','treeGrid','layer','jquery'],function(){
    var form = layui.form,
        element = layui.element;
    $ = layui.$;
    var layer = parent.layer === undefined ? layui.layer : top.layer;
    var table = layui.table;
    var laytpl = layui.laytpl;
    var layedit = layui.layedit;

    //列表数据
    var option = {
        elem: '#tableList',
        url : '/api/agt_agritech/page',
        cellMinWidth : 95,
        page : true,
        height : "full-125",
        limits : [10,15,20,25],
        limit : 15,
        id : "listTable",
        cols : [[
            {type: "checkbox", fixed:"left", width:50, style:'height: 71px;'},
            {field: 'id', title: '农技ID', minWidth:100, align:"center"},
            {field: 'agritechCover', title: '农技封面', width:200, align:"center", templet:'<div><img style="height: 60px;" src="{{d.agritechCover}}"></div>'},
            {field: 'speciesId', title: '物种', minWidth:100, align:"center", templet:function (d) {
                    var speciesName = '';
                    $.ajax({
                        url : '/api/agt_species/' + d.speciesId,
                        async:false,
                        success: function (data) {
                            speciesName = data.speciesName;
                        }
                    });
                    return (speciesName == '' || speciesName == null) ? "无" : speciesName;
                }},
            {field: 'agritechTitle', title: '农技标题', minWidth:200, align:'center', templet:function (d) {
                    return d.agritechTitle.length < 20 ? d.agritechTitle : d.agritechTitle.substring(0, 20) + "...";
                }},
            {field: 'agritechAbstract', title: '农技摘要', minWidth:200, align:"center", templet:function (d) {
                    return d.agritechAbstract.length < 20 ? d.agritechAbstract : d.agritechAbstract.substring(0, 20) + "...";
                }},
            /*{field: 'agritechContent', title: '农技内容', minWidth:200, align:"center", templet:function (d) {
                    return d.agritechContent.length < 50 ? d.agritechContent : d.agritechContent.substring(0, 50) + "...";
                }},*/
            {field: 'createdBy', title: '创建者', minWidth:100, align:"center", templet:function (d) {
                    var createdBy = '';
                    if (d.createdBy != null) {
                        $.ajax({
                            url : '/user/' + d.createdBy,
                            async:false,
                            success: function (data) {
                                createdBy = data.loginName;
                            }
                        });
                    }
                    return (createdBy == '' || createdBy == null) ? "无" : createdBy + "(ID:"+d.createdBy+")";
                }},
            {field: 'updatedTime', title: '更新时间', align:'center',minWidth:160,sort:true, templet:function(d){
                    //处理时间
                    return new Date(d.updatedTime).Format("yyyy-MM-dd hh:mm:ss");
                    // return new Date(d.updatedTime).toLocaleString();
                }
            },
            {field: 'createdTime', title: '创建时间', align:'center',minWidth:160,sort:true, templet:function(d){
                    //处理时间
                    return new Date(d.createdTime).Format("yyyy-MM-dd hh:mm:ss");
                    // return new Date(d.createdTime).toLocaleString();
                }
            },
            {title: '操作', minWidth:200, templet:'#tableListBar',fixed:"right",align:"center", style:'height: 71px;'}
        ]]
    };

    //场景数据
    var height = $(document).height();
    $(".orgbox").css('height',(height - 40) + "px");
    $(window).on("resize",function () {
        $(".orgbox").css('height',(height - 40) + "px");
    });
    var treeData = {
        elem: '#tree' //指定元素
        , target: '_blank' //是否新选项卡打开（比如节点返回href才有效）
        , click: function (item) { //点击节点回调
            option.url = '/api/agt_agritech/query';
            option.where = {speciesId: item.id};
            console.log(option);
            table.render(option);
        }
        ,nodes:null
    };
    //异步加载农技
    $.get('/api/agt_species/tree',function(data) {
        if (data.data.length != 0) {
            data.data[0].spread = true;
        }
        data = JSON.stringify(data.data).replace(/speciesName/g, "name");
        treeData.nodes = JSON.parse(data);
        // treeData.nodes = data.data;
        layui.tree(treeData);
    });

    //农技列表
    var tableIns = table.render(option);

    //搜索农技信息
    $(".search_btn").on("click",function(){
        var searchKey = $(".searchVal").val();
        if(searchKey != ''){
            option.url = '/api/agt_agritech/query';
            option.method = 'post';
            option.where = {name: searchKey};
            table.render(option);
        }else{
            layer.msg("请输入搜索的内容");
        }
    });

    //添加农技
    $(".addBtn").click(function(){
        var index = layui.layer.open({
            title : "添加农技",
            type : 2,
            content : "agritechAdd",
            area: ['100%',$(document).height() + 'px'],
            success : function(layero, index){
                setTimeout(function(){
                    layui.layer.tips('点击此处返回农技列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                },500)
            }
        });
        layui.layer.full(index);
        //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
        $(window).on("resize",function(){
            layui.layer.full(index);
        });
    });

    //批量删除
    $(".delAll_btn").click(function(){
        var checkStatus = table.checkStatus('listTable'),//此处的id为table数据格式中的id
            data = checkStatus.data,
            idArr = [];
        if(data.length > 0) {
            for (var i in data) {
                idArr.push(data[i].id);
            }
            layer.confirm('确定删除选中的农技？', {icon: 3, title: '提示信息'}, function (index) {
                for(var i=0;i<idArr.length;i++){
                    $.get("/api/agt_agritech/delete?id=" + idArr[i],function(data){
                        if (data.code == 200) {
                            layer.msg("删除成功！");
                        } else {
                            layer.msg("删除失败，请重试！");
                        }
                        tableIns.reload();
                        layer.close(index);
                    });
                }
            })
        }else{
            layer.msg("请选择需要删除的农技");
        }
    });

    //列表操作
    table.on('tool(tableList)', function(obj){
        var layEvent = obj.event,
            data = obj.data;
        if(layEvent === 'edit'){ //编辑
            var index = layui.layer.open({
                title : "修改农技信息",
                type : 2,
                content : "agritechEdit?id=" + data.id,
                area: ['100%',$(document).height() - 30 + 'px'],
                success : function(){
                    setTimeout(function(){
                        layui.layer.tips('点击此处返回农技列表', '.layui-layer-setwin .layui-layer-close', {
                            tips: 3
                        });
                    },500);
                }
            });
            layui.layer.full(index);
            //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
            $(window).on("resize",function(){
                layui.layer.full(index);
            });
        }else if(layEvent === 'config') { //配置农技规格信息
            var index = layui.layer.open({
                title: "农技配置",
                type: 2,
                content: "config/configIndex?id=" + data.id,
                area: ['100%',($(document).height() - 40) + 'px'],
                success: function () {
                    setTimeout(function () {
                        layui.layer.tips('点击此处返回农技列表', '.layui-layer-setwin .layui-layer-close', {
                            tips: 3
                        });
                    }, 500);
                }
            });
            layui.layer.full(index);
            //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
            $(window).on("resize", function () {
                layui.layer.full(index);
            });
        }else if(layEvent === 'del'){ //删除
            layer.confirm('确定删除此农技？',{icon:3, title:'提示信息'},function(index){
                $.get("/api/agt_agritech/delete?id=" + data.id,function(data){
                    if (data.code == 200) {
                        layer.msg("删除成功！");
                    } else {
                        layer.msg("删除失败，请重试！");
                    }
                    tableIns.reload();
                    layer.close(index);
                });
            });
        }
    });

    Date.prototype.Format = function(fmt)
    { //author: meizz
        var o = {
            "M+" : this.getMonth()+1,                 //月份
            "d+" : this.getDate(),                    //日
            "h+" : this.getHours(),                   //小时
            "m+" : this.getMinutes(),                 //分
            "s+" : this.getSeconds(),                 //秒
            "q+" : Math.floor((this.getMonth()+3)/3), //季度
            "S"  : this.getMilliseconds()             //毫秒
        };
        if(/(y+)/.test(fmt))
            fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
        for(var k in o)
            if(new RegExp("("+ k +")").test(fmt))
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
        return fmt;
    }

});